package com.connect.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * Socket通信
 *
 */
public class HexScoketService
{

    String strReturn;
    public String getHex(Socket socket,SocketAddress address,String hexStr,int open,int lengthBuf) throws IOException {


        try {
//            System.out.println("connecting...");

//            System.out.println("connection success");

                String str = hexStr; //发送的16进制字符串
                byte[] bytes = hexStringToByteArray(str);
//                System.out.println(bytes);
                OutputStream os = socket.getOutputStream();
                os.write(bytes);
                //输入流
                InputStream in=socket.getInputStream();
                //接收服务器的响应
                int line = 0;
                byte[] buf = new byte[lengthBuf];
                //接收收到的数据
                int len = in.read(buf);
                strReturn= BinaryToHexString(buf);
//                System.out.println(strReturn);
                os.flush();
//                os.close();
//                Thread.sleep(100);
                return strReturn;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
            if (open != 1) {
               socket.close();
            }}catch (Exception e){
                e.toString();
            }
        }
        return strReturn;
    }

    /**
     * 16进制表示的字符串转换为字节数组
     *
     * @param hexString 16进制表示的字符串
     * @return byte[] 字节数组
     */
    public static byte[] hexStringToByteArray(String hexString) {
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
                    .digit(hexString.charAt(i + 1), 16));
        }
        return bytes;
    }

    /**
     * 将字节数组转换成十六进制的字符串
     *
     * @return
     */
    public static String BinaryToHexString(byte[] bytes) {
        String hexStr = "0123456789ABCDEF";
        String result = "";
        String hex = "";
        for (byte b : bytes) {
            hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
            hex += String.valueOf(hexStr.charAt(b & 0x0F));
            result += hex + " ";
        }
        return result;
    }

}
